﻿using MediatR;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RedDragon.Common.Domain.Enterprise;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Dtos;
using RedDragon.ERP.API.Application.Commands.Supplieries;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 导出采购/委外信息
    /// </summary>
    public class ExportPurchaseHandler : IRequestHandler<ExportPurchaseCommand, FileExportResult>
    {
        private readonly ISqlSugarClient _db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ExportPurchaseHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public ExportPurchaseHandler(ISqlSugarClient db, ILogger<ExportPurchaseHandler> logger)
        {
            _db = db;
            _logger = logger;
        }

        /// <summary>
        /// 导出采购/委外信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<FileExportResult> Handle(ExportPurchaseCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();
            try
            {
                //六表联查
                var query = await _db.Queryable<PurchaseOutsources, PurchaseType, AffiliatedProject, Currency, Suppliers, Departments>((p, t, a, c, s, d) => p.PurchaseTypeId == t.PurchaseTypeId && p.AffiliatedProjectId == a.AffiliatedProjectId && p.CurrencyId == c.CurrencyId && p.SupplierId == s.SupplierId && p.DepartmentId == d.DepartmentId)
                    .Select((p, t, a, c, s, d) => new PurchaseOutsourcesDto()
                    {
                        PurchaseId = p.PurchaseId,
                        PurchaseNumber = p.PurchaseNumber,
                        PurchaseName = p.PurchaseName,
                        PurchaseTypeId = p.PurchaseTypeId,
                        AffiliatedProjectId = p.AffiliatedProjectId,
                        ProtocolCoding = p.ProtocolCoding,
                        ProtocolName = p.ProtocolName,
                        PurchaseNote = p.PurchaseNote,
                        SupplierId = p.SupplierId,
                        CurrencyId = p.CurrencyId,
                        PaymentAmount = p.PaymentAmount,
                        StartTime = p.StartTime,
                        EndTime = p.EndTime,
                        TheDateOfSigning = p.TheDateOfSigning,
                        PurchaseStatus = p.PurchaseStatus,
                        TaxType = p.TaxType,
                        TaxRate = p.TaxRate,
                        PreparedBy = p.PreparedBy,
                        DepartmentId = p.DepartmentId,
                        CreatedOwner = p.CreatedOwner,
                        CreatedTime = p.CreatedTime,
                        UpdateOwner = p.UpdateOwner,
                        UpdateTime = p.UpdateTime,
                        ExamineOwner = p.ExamineOwner,
                        ExamineTime = p.ExamineTime,
                        ApprovalStatus = p.ApprovalStatus,
                        AffiliatedProjectName = a.AffiliatedProjectName,
                        PurchaseTypeName = t.PurchaseTypeName,
                        CurrencyName = c.CurrencyName,
                        SupplierName = s.SupplierName,
                        DepartmentName = d.DepartmentName,
                    }).ToListAsync();

                //创建一个新的Excel工作簿
                IWorkbook wb = new XSSFWorkbook();

                //在工作簿中创建一个新的Sheet
                ISheet sheet = wb.CreateSheet();

                //创建表头,第一行
                IRow row = sheet.CreateRow(0);

                //设置表头的各个列标题
                row.CreateCell(0).SetCellValue("序号");
                row.CreateCell(1).SetCellValue("订单编码");
                row.CreateCell(2).SetCellValue("订单名称");
                row.CreateCell(3).SetCellValue("订单类型");
                row.CreateCell(4).SetCellValue("所属项目");
                row.CreateCell(5).SetCellValue("供应商");
                row.CreateCell(6).SetCellValue("签订日期");
                row.CreateCell(7).SetCellValue("制单人");
                row.CreateCell(8).SetCellValue("制单部门");
                row.CreateCell(9).SetCellValue("创建时间");
                row.CreateCell(10).SetCellValue("状态");
                row.CreateCell(11).SetCellValue("审批状态");

                //初始化行索引
                int index = 0;//注意这里从0行开始 已经是表头了
                foreach (var item in query)
                {
                    //为每条记录创建一行
                    row = sheet.CreateRow(index);

                    //填充数据到各列
                    row.CreateCell(0).SetCellValue(item.PurchaseId);
                    row.CreateCell(1).SetCellValue(item.PurchaseNumber);
                    row.CreateCell(2).SetCellValue(item.PurchaseName);
                    row.CreateCell(3).SetCellValue(item.PurchaseTypeName);
                    row.CreateCell(4).SetCellValue(item.AffiliatedProjectName);
                    row.CreateCell(5).SetCellValue(item.SupplierName);
                    row.CreateCell(6).SetCellValue(item.TheDateOfSigning.ToString());
                    row.CreateCell(7).SetCellValue(item.PreparedBy);
                    row.CreateCell(8).SetCellValue(item.DepartmentName);
                    row.CreateCell(9).SetCellValue(item.CreatedTime.ToString());
                    row.CreateCell(10).SetCellValue(item.PurchaseStatus);
                    row.CreateCell(11).SetCellValue(item.ApprovalStatus);

                    //行索引递增
                    index++;
                }

                //将工作簿内容写入字节数组
                byte[] bytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    wb.Write(ms);
                    bytes = ms.ToArray();
                }

                //获取.xlsx文件的MIME类型
                string mime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

                //设置导出结果对象的属性
                result.FileBytes = bytes;//文件字节内容
                result.MimeType = mime;//MIME类型
                result.FileName = "采购/委外订单信息.xlsx";//文件名
            }
            catch (Exception ex)
            {
                _logger.LogError("导出采购/委外订单信息信息异常" + ex.Message);
            }
            return result;
        }
    }
}
